import { useState, useEffect } from 'react';
import { Form, Select, Spin } from 'antd';
import { axconst } from '@/shared/axconst';
import { AxValidator } from '../AxValidator';
import debounce from 'lodash/debounce';

const FormItem = Form.Item;
const { Option } = Select;
const {
  inlineFormItemLayout,
  inlineFormItemLayoutAllRowTwo,
  inlineFormItemLayoutAllRowThree,
} = axconst;
/**
 * 自定义搜索下拉框
 * @param label 标签
 * @param field 字段名称
 * @param value 值
 * @param mode 模式 'multiple' | 'tags' | '-'
 * @param @param allowClear 允许为空（默认：true）
 * @param showLabel 是否展示label（默认true）
 * @param placeholder 占位符
 * @param required 是否必填
 * @param message 提示信息（如果添加了，所有错误提示为改信息）
 * @param validator 自定义验证函数
 * @param hidden 是否隐藏
 * @param valueField 值字段（id）
 * @param displayField 名称字段（name）
 * @param displayExtraField 额外的展示字段（如：idcard）
 * @param searchField 查询字段（name）
 * @param handleRead 数据请求接口
 */
export function AxSelectSearchRemote(props) {
  const [data, setData] = useState([]);
  const [fetching, setFetching] = useState(false);
  const {
    label,
    hidden,
    form,
    field,
    value,
    required,
    message,
    validator,
    mode,
    placeholder,
    showLabel = true,
    wholerow,
    showSearch = true,
    allowClear = true,
    formItemLayoutFromProps = null,
    valueField = 'id',
    displayField = 'name',
    displayExtraField,
    searchField = 'name',
    handleRead,
    ...rest
  } = props;
  let formItemLayout = {};
  switch (wholerow) {
    case 'two':
      formItemLayout = { ...inlineFormItemLayoutAllRowTwo };
      break;
    case 'three':
      formItemLayout = { ...inlineFormItemLayoutAllRowThree };
      break;
    default:
      formItemLayout = formItemLayoutFromProps
        ? formItemLayoutFromProps
        : { ...inlineFormItemLayout };
      break;
  }

  useEffect(() => {
    handleRead().then(res => {
      if (displayExtraField) {
        setData(res.list.map(i => {
          i[displayField] = i[displayField] + "(" + i[displayExtraField] + ")";
          return i;
        }));
      }
      else setData(res.list);
    });
  }, [])

  const handleSearch = debounce((v) => {
    if (handleRead) {
      const params = {};
      params[searchField] = v;
      setData([]);
      setFetching(true);
      handleRead(params).then(res => {
        setFetching(false);
        if (displayExtraField) {
          setData(res.list.map(i => {
            i[displayField] = i[displayField] + "(" + i[displayExtraField] + ")";
            return i;
          }));
        }
        else setData(res.list);
      });
    }
  }, 800);
  return hidden ? null : (
    <FormItem {...formItemLayout} label={showLabel === true ? label : ''}>
      {form.getFieldDecorator(field, {
        initialValue: value,
        rules: [
          {
            label: label,
            required: required,
            message: message,
            validator: validator ? validator : AxValidator,
          },
        ],
      })(
        <Select
          allowClear={allowClear}
          showSearch={showSearch}
          style={{ width: '100%' }}
          mode={mode ? mode : '-'}
          placeholder={placeholder ? placeholder : `请选择${label}`}
          notFoundContent={fetching ? <Spin size="small" /> : null}
          filterOption={false}
          onSearch={handleSearch}
          {...rest}
        >
          {data &&
            data.map &&
            data.map((d, idx) => (
              <Option key={idx} value={d[valueField]}>
                {d[displayField]}
              </Option>
            ))}
        </Select>,
      )}
    </FormItem>
  );
}
